import getLastEvent from "../utils/getLastEvent"
import getSelector from '../utils/getSelector'
import getStack from '../utils/getStack'
import request from '../utils/request'
export function injectPromiseError(){
    window.addEventListener('unhandledrejection', function (event){
        console.log('in unhandledrejection listener');
        console.log(event)
        let lastEvent = getLastEvent();
        let log = {
            kind: 'stability',//大分类
            type: 'error',//小类型
            errorType: 'promiseError',//小小类型
            message: '',//报错信息
            filename: '',
            position: '',
            stack: '',
            selector: getSelector(lastEvent)
        }
        if(typeof event.reason ==='string'){
            log.message = event.reason;
            log.filename = event.currentTarget.origin;
            log.position = `can not detect`
            log.stack = 'This is a intentionally promise error by Promise.reject()'
        } else if(typeof event.reason ==='object'){
            log.message = event.reason.message;
            //at http://localhost:8080/:23:38
            if(event.reason.stack){
                let matchResult = event.reason.stack.match(/at\s+(.+):(\d+):(\d+)/);
                log.filename = matchResult[1];
                let line = matchResult[2],
                    column = matchResult[3];
                log.position = `${line}:${column}`
                log.stack = event.reason.stack;
            }
        }
        request.send(log).then(res => {
            console.log(res);
        })
    },true)
}